package cn.com.yusys.yusp.message.web.rest;

import cn.com.yusys.yusp.commons.exception.Message;
import cn.com.yusys.yusp.commons.exception.MessageConstants;
import cn.com.yusys.yusp.commons.exception.YuspException;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.service.CommonService;
import cn.com.yusys.yusp.commons.web.rest.CommonResource;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;
import cn.com.yusys.yusp.message.domain.MessageSubscribe;
import cn.com.yusys.yusp.message.domain.MessageTemp;
import cn.com.yusys.yusp.message.domain.MessageType;
import cn.com.yusys.yusp.message.service.MessageTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/template")
public class MessageResource extends CommonResource<MessageType, String> {


    private Logger logger = LoggerFactory.getLogger(MessageResource.class);

    @Autowired
    private MessageTypeService service;

    @Override
    protected CommonService getCommonService() {
        return this.service;
    }

    @GetMapping("/getMessageTypeList")
    protected ResultDto<List<Map<String, Object>>> getMessageTypeList(QueryModel queryModel) {
        logger.debug("REST request to query index : {}", queryModel);
        if (queryModel.getCondition().containsKey("messageDesc")) {
            queryModel.getCondition().put("messageDesc", "%" + queryModel.getCondition().get("messageDesc") + "%");
        }

        List<Map<String, Object>> list = service.queryMessageType(queryModel);
        return new ResultDto<List<Map<String, Object>>>(list);
    }

    @PostMapping("/addMessageType")
    protected ResultDto<Integer> addMessageType(@RequestBody MessageType t) throws Exception {
        logger.debug("REST request to save Object : {}", t);
        MessageType messageType = service.selectByPrimaryKey(t.getMessageType());
        if (null != messageType) {
            return new ResultDto<Integer>(1);
        }
        getCommonService().insert(t);
        return new ResultDto<Integer>(0);
    }

    @PostMapping("/editMessageType")
    protected ResultDto<Integer> editMessageType(@RequestBody MessageType t) throws Exception {
        logger.debug("REST request to save Object : {}", t);
        service.updateSelective(t);
        return new ResultDto<Integer>(0);
    }

    @PostMapping("/deleteMessageType/{id}")
    ResultDto<Integer> deleteMessageType(@PathVariable String id) {
        logger.debug("REST request to delete Object : {}", id);
        int result = getCommonService().deleteByPrimaryKey(id);
        // 删除消息模板
        MessageTemp param = new MessageTemp();
        param.setMessageType(id);
        service.deleteTemplate(param);
        return new ResultDto<Integer>(result);
    }

    @PostMapping("/addOrUpdateTemplate/")
    ResultDto<Integer> addOrUpdateTemplate(@RequestBody MessageTemp messageTemp) {
        int result = service.addOrUpdateTemplate(messageTemp);
        return new ResultDto<Integer>(result);
    }

    @PostMapping("/deleteTemplate/")
    ResultDto<Integer> deleteTemplate(@RequestBody MessageTemp messageTemp) {
        if (null == messageTemp.getChannelType() || null == messageTemp.getMessageType()) {
            return new ResultDto<Integer>(1);
        }
        int result = service.deleteTemplate(messageTemp);
        return new ResultDto<Integer>(result);
    }

    @PostMapping("/getTemplateInfo/")
    ResultDto<MessageTemp> getTemplateInfo(@RequestBody MessageTemp messageTemp) {
        MessageTemp result = service.getTemplateInfo(messageTemp);
        return new ResultDto<MessageTemp>(result);
    }

    @GetMapping("/getChannelSubscribeList")
    protected ResultDto<List<Map<String, Object>>> getChannelSubscribeList(QueryModel queryModel) {
        String messageDesc = (String) (queryModel.getCondition().get("messageDesc"));
        if (null != messageDesc && !"".equals(messageDesc)) {
            queryModel.getCondition().put("messageDesc", "%" + messageDesc + "%");
        }
        String messageType = (String) (queryModel.getCondition().get("messageType"));
        if (null != messageType && !"".equals(messageType)) {
            queryModel.getCondition().put("messageType", "%" + messageType + "%");
        }
        queryModel.getCondition().put("templateType", "D");
        List<Map<String, Object>> list = service.queryMessageTypeAndChannel(queryModel);
        return new ResultDto<List<Map<String, Object>>>(list);
    }

    @PostMapping("/getSubscribe/")
    ResultDto<String> getSubscribe(@RequestBody MessageSubscribe messageSubscribe) {
        logger.debug("Get subscription information!");
        String subscribeValue = "";
        ResultDto<String> resultDto = new ResultDto<>();
        try {
            if (messageSubscribe.getChannelType() != null && messageSubscribe.getMessageType() != null
                    && messageSubscribe.getSubscribeType() != null) {
                List<MessageSubscribe> result = service.getSubscribeInfo(messageSubscribe);
                for (MessageSubscribe messageSubscribeT : result) {
                    if (null != messageSubscribeT.getSubscribeValue()) {
                        subscribeValue = subscribeValue + messageSubscribeT.getSubscribeValue().trim() + ",";
                    }

                }
                if (subscribeValue.endsWith(",")) {
                    subscribeValue = subscribeValue.substring(0, subscribeValue.length() - 1);
                }
            }
            resultDto.setData(subscribeValue);
            resultDto.setMessage("获取订阅信息成功!");
        } catch (Exception e) {
            resultDto.setCode(500);
            resultDto.setMessage(e.getMessage());
        }
        return resultDto;
    }

    @PostMapping("/saveSubscribe/")
    ResultDto<String> saveSubscribe(@RequestBody MessageSubscribe messageSubscribe) {
        logger.debug("Save subscription information!");
        ResultDto<String> resultDto = new ResultDto<>();
        try {
            if (messageSubscribe.getChannelType() != null && messageSubscribe.getMessageType() != null
                    && messageSubscribe.getSubscribeType() != null
                    && messageSubscribe.getSubscribeValue() != null) {
                service.addOrUpdateMessageSubscribe(messageSubscribe);
            } else {
                throw new YuspException(new Message("500", "part of parameters is null", MessageConstants.MSG_LEVEL_ERROR));
            }
            resultDto.setData("0");
            resultDto.setMessage("保存订阅信息成功!");
        } catch (Exception e) {
            resultDto.setCode(Integer.parseInt("500"));
            resultDto.setMessage(e.getMessage());
        }
        return resultDto;
    }

    @GetMapping("/queryMessageResult")
    protected ResultDto<List<Map<String, Object>>> queryMessageResult(QueryModel queryModel) {
        if (queryModel.getCondition().containsKey("userNo")) {
            queryModel.getCondition().put("userNo", "%" + queryModel.getCondition().get("userNo") + "%");
        }
        if (queryModel.getCondition().containsKey("sendTime")) {
            queryModel.getCondition().put("sendTime", "%" + queryModel.getCondition().get("sendTime") + "%");
        }

        List<Map<String, Object>> list = service.queryMessageResult(queryModel);
        return new ResultDto<List<Map<String, Object>>>(list);
    }

    @GetMapping("/queryMessagePool")
    protected ResultDto<List<Map<String, Object>>> queryMessagePool(QueryModel queryModel) {
        if (queryModel.getCondition().containsKey("userNo")) {
            queryModel.getCondition().put("userNo", "%" + queryModel.getCondition().get("userNo") + "%");
        }
        if (queryModel.getCondition().containsKey("createTime")) {
            queryModel.getCondition().put("createTime", "%" + queryModel.getCondition().get("createTime") + "%");
        }

        List<Map<String, Object>> list = service.queryMessagePool(queryModel);
        return new ResultDto<List<Map<String, Object>>>(list);
    }

    @SuppressWarnings("rawtypes")
    @PostMapping("/top")
    protected ResultDto<Integer> top(@RequestBody Map param) {
        if (!param.containsKey("pkNos")) {
            return new ResultDto<Integer>(1);
        } else {
            String[] pkNos = ((String) param.get("pkNos")).trim().split(",");
            return new ResultDto<Integer>(service.top(pkNos));
        }


    }

    @SuppressWarnings("rawtypes")
    @PostMapping("/sendAgain")
    protected ResultDto<Integer> sendAgain(@RequestBody Map param) {
        logger.debug("Resend message!");
        ResultDto<Integer> resultDto = new ResultDto<>();
        if (!param.containsKey("pkNos")) {
            resultDto.setMessage("缺失必要参数!");
            resultDto.setData(1);
        } else {
            String[] pkNos = ((String) param.get("pkNos")).trim().split(",");
            int result = service.sendAgain(pkNos);
            resultDto.setData(result);
            resultDto.setMessage("消息发送成功!");
        }
        return resultDto;
    }


    @PostMapping("/sendMessageTest/{id}")
    protected ResultDto<Integer> sendMessageTest(@PathVariable String id) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("test", " 测试占位符");
        param.put("sendUserId", "40");

        service.sendRealTimeMessageWithTemplate(id, null, "40,40", param);
        service.sendRealTimeMessageWithOutTemplate("system", "40,40", "hello hello", new HashMap<String, String>());
        service.sendSubscribeMessage(id, null, param);
        return new ResultDto<Integer>(0);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @PostMapping("/sendRealTimeMessageWithOutTemplate")
    public String sendRealTimeMessageWithOutTemplate(@RequestBody Map param) {
        String channelType = (String) param.get("channelType");
        if (null == channelType || "".equals(channelType)) {
            return "渠道类型为空";
        }

        String users = (String) param.get("users");
        if (null == users || "".equals(users)) {
            return "用户为空";
        }

        String content = (String) param.get("content");
        if (null == content || "".equals(content)) {
            return "内容为空";
        }
        service.sendRealTimeMessageWithOutTemplate(channelType, users, content, param);
        return "0";
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @PostMapping("/sendRealTimeMessageWithTemplate")
    public String sendRealTimeMessageWithTemplate(@RequestBody Map param) {
        String messageType = (String) param.get("messageType");
        if (null == messageType || "".equals(messageType)) {
            return "消息类型为空";
        }

        String channelType = (String) param.get("channelType");

        String users = (String) param.get("users");

        service.sendRealTimeMessageWithTemplate(messageType, channelType, users, param);
        return "0";
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @PostMapping("/sendSubscribeMessage")
    public String sendSubscribeMessage(@RequestBody Map param) {
        String messageType = (String) param.get("messageType");
        if (null == messageType || "".equals(messageType)) {
            return "消息类型为空";
        }
        String channelType = (String) param.get("channelType");
        service.sendSubscribeMessage(messageType, channelType, param);
        return "0";
    }

}
